package com.sunky.rfidapp

import com.sunky.db.greendao.UserConfigDao
import com.sunky.db.model.UserConfig
import com.sunky.db.util.DBManager
import com.sunky.db.util.getFirst
import com.sunky.db.util.saveJustOne
import com.sunky.rfidapp.network.NetBuilder
import com.sunky.rfidapp.network.RequestManager
import kotlinx.android.synthetic.main.activity_config.*
import kotlinx.android.synthetic.main.layout_title.*

class ConfigActivity : BaseActivity() {

    private lateinit var mDao: UserConfigDao

    private var userConfig: UserConfig? = null

    private var downTime = 0L

    override fun getLayoutId(): Int {
        return R.layout.activity_config
    }

    override fun initView() {
        TvTitle.text = getString(R.string.title_config)
        TvReturn.setOnClickListener {
            finish()
        }
        TvSave.setOnClickListener {
            if (EtDeviceNo.text.toString().isEmpty()) {
                toast(getString(R.string.toast_input_device_no))
                return@setOnClickListener
            }
            if (EtServerAddr.text.toString().isEmpty()) {
                toast(getString(R.string.toast_input_server_addr))
                return@setOnClickListener
            }
            UserConfig(EtDeviceNo.text.toString(),EtServerAddr.text.toString()).apply {
                DBManager.getInstance().saveJustOne(mDao,this)
                toast(getString(R.string.toast_save_success))
                NetBuilder.sUrl = EtServerAddr.text.toString()
                NetBuilder.sCode = EtDeviceNo.text.toString()
                NetBuilder.getInstance().refreshRetrofit()
                RequestManager.refreshService()
                finish()
            }
        }
        hiddenButton.setOnClickListener {
            var current = System.currentTimeMillis()
            if (current - downTime < 500){
                if (isDebugOn()){
                    toast("关闭调试信息")
                    setDebug(false)
                }else{
                    toast("打开调试信息")
                    setDebug(true)
                }
            }
            downTime = current
        }
    }

    override fun initData() {
        mDao = DBManager.getInstance().daoSession.userConfigDao
        userConfig = DBManager.getInstance().getFirst(mDao)?.apply {
            EtDeviceNo.setText(this.deviceNo)
            EtServerAddr.setText(this.serverAddr)
        }
    }

    private fun isDebugOn():Boolean{
        return getSharedPreferences("config",0).getBoolean("is_debug_on",false)
    }

    private fun setDebug(on:Boolean){
        getSharedPreferences("config",0).edit().putBoolean("is_debug_on",on).commit()
    }
}